package com.weng.coder.service;

import java.beans.Transient;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.coder.common.model.File;
import com.weng.coder.entity.CodeTable;
import com.weng.coder.entity.Project;
import com.weng.coder.mapper.CodeTableMapper;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.dao.mybatis.model.page.PageModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.weng.coder.mapper.FieldMapper;
import com.weng.coder.entity.Field;
import org.springframework.transaction.annotation.Transactional;


/**
 * 字段 业务实现类
 *
 * @作者 wengzhonghui
 * @创建时间 2018-02-24 20:39:08
 */
@Service("fieldService")
@Slf4j
public class FieldServiceImpl implements FieldService {
	
	@Resource
	private FieldMapper fieldDao;
	@Resource
	private CodeTableMapper codeTableDao;
	@Resource
	private GetTableAndFieldsBySqlService getTableAndFieldsBySqlService;

	
	public List<Field> findByIds(List<String> ids){
		return fieldDao.selectBatchIds(ids);
	}
	/**
	 * Save
	 * @param t
	 */
	@Transactional
	@Override
	public Field save(Field t) {
			if(StringUtils.isEmpty(t.getId())){
					fieldDao.insert(t);
			}else{
					fieldDao.updateById(t);
			}
		return t;
	}

	@Override
	public void delete(String id) {
		fieldDao.deleteById(id);
	}



	@SuppressWarnings("unchecked")
	@Override
	public IPage<Field> getDataByPage(int pageNo, int pageSize, Field t) {

		QueryWrapper<Field> qw = new QueryWrapper<Field>();
		if(t.getTableId()!=null) qw.eq("TABLE_ID", t.getTableId());
		if(t.getName()!=null) qw.like("NAME", "%"+ t.getName() +"%");
		IPage<Field> page = new PageModel<>(pageNo,pageSize);
		return this.fieldDao.selectPage(page, qw);
	}

	

	@Override
	public void delete(Field t) {
		fieldDao.deleteById(t.getId());
	}
	

	@Override
	public Field getOne(String id) {
		
		return this.fieldDao.selectById(id);
		
	}

	@Override
	public boolean exists(String id) {
		return getOne(id) != null;
	}

	@Override
	public void delete(Iterable<Field> entities) {
		if(entities!=null){
			for(Field t:entities){
				fieldDao.deleteById(t.getId());
			}
		}
	}

	@Override
	public void deleteByIds(String[] ids) {
		if(ids!=null && ids.length>0){
			for(String id:ids){
				fieldDao.deleteById(id);
			}
		}
	}
	
	@Override
	@Transactional
	public void deleteByProjectId(String projectId) {

		QueryWrapper<CodeTable> qwTable = new QueryWrapper<>();
		qwTable.eq("PROJECT_ID", projectId);
		List<CodeTable> list = this.codeTableDao.selectList(qwTable);
		List<String> tableIds = new ArrayList<>();
		if(list != null){
			for(CodeTable codeTable : list){
				tableIds.add(codeTable.getId());
			}
		}
		if(tableIds != null && tableIds.size() >0){
				QueryWrapper<Field> qwField = new QueryWrapper<>();
				qwField.in("TABLE_ID", tableIds);
				this.fieldDao.delete(qwField);
		}
	}
    @Override
	public void deleteByTableId(String tableId){
		QueryWrapper<Field> qwField = new QueryWrapper<>();
		qwField.eq("TABLE_ID", tableId);
		 this.fieldDao.delete(qwField);
	}

	@Override
	public List<Field> findByTableId(String tableId){
		QueryWrapper<Field> qwField = new QueryWrapper<>();
		qwField.eq("TABLE_ID", tableId);
		return this.fieldDao.selectList(qwField);
	}

	@Override
	public ResponseData addFieldsBySql(String tableId, String sql, HttpServletRequest request){
		
		StringBuilder fieldNames = new StringBuilder();
		StringBuilder existsFieldNames = new StringBuilder();
		if(StringUtils.isEmpty(tableId)){
			return ResponseData.failed("所属的表格ID不能为空!");
		}
		List<CodeTable> tableList = getTableAndFieldsBySqlService.getTableListBySql(null, sql);
		if(tableList!=null && tableList.size()>0){
			if(tableList.size()>1){
				return ResponseData.failed("创建失败！一次只能输入一个建表脚本！");
			}
			try {
				CodeTable table = tableList.get(0);
				List<Field> fieldList = table.getFieldList();
				if(fieldList!=null && fieldList.size()>0){
					List<Field> existsFieldList = findByTableId(tableId);
					for(Field field : fieldList){
						
						if(isFieldExists(field.getName(), existsFieldList)){
							if(existsFieldNames.length()>0){
								existsFieldNames.append(",");
							}
							existsFieldNames.append(field.getName());
							continue;
						}
						if(fieldNames.length()>0){
							fieldNames.append(",");
						}
						fieldNames.append(field.getName());
						field.setTableId(tableId);
						this.save(field);
					}
				}else{
					return ResponseData.failed("创建失败！该建表脚本不包括任何列属性！");
				}
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return ResponseData.failed("生成异常，请联系管理员，错误信息为：" + e.getMessage());
			}
			
		}else{
			return ResponseData.failed("请输入规范的SQL，未找到任何一个建库脚本！");
		}
		StringBuilder successMsg = new StringBuilder("添加成功");
		if(fieldNames.length()>0){
			successMsg.append(" ,成功添加字段：" + fieldNames.toString());
		}
		if(existsFieldNames.length()>0){
			successMsg.append(" ,以下字段已经存在不重复添加：" + existsFieldNames.toString());
		}
		return ResponseData.success(successMsg.toString());
	
	}
	
	/**
	 * 判断Table是否已存在
	 * @return
	 */
	private boolean isFieldExists(String name, List<Field> existsFieldList){
		if(existsFieldList!=null && existsFieldList.size()>0){
			for(Field oldField: existsFieldList){
				if(name.equalsIgnoreCase(oldField.getName())){
					return true;
				}
			}
		}
		return false;
	}

	public List<Field> findByColumnAndTableId(String column, String tableId){
		QueryWrapper<Field> qw = new QueryWrapper<>();
		qw.eq("data_column",column);
		qw.eq("TABLE_ID", tableId);
		return this.fieldDao.selectList(qw);
	}

	
}
